<?php
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';
require_once dirname(__FILE__) . '/../../../incls/php/ecomutils.class.php';

session_name(SESSION);
session_start();

$myPdo = DbUtils::createPdoInst();
$page_id = MiscUtils::getParam('i', 0);
$active_tab = MiscUtils::getParam('at', 0);

$sys_script = 'index';

if (isset($_COOKIE['my_cart'])) {
  $_SESSION['my_cart'] = json_decode($_COOKIE['my_cart']);
}

if (!isset($_SESSION['my_cart'])) {
  $_SESSION['my_cart'] = array();
}

EComUtils::update_cart($myPdo, $_SESSION['my_cart'], isset($_SESSION['index' . USER]) ? $_SESSION['index' . USER] : NULL);

foreach ($_SESSION['my_cart'] as $idx => $pur) {
  unset($_SESSION['stock_err' . $idx]);
  if ($pur->_stock < $pur->quantity && $pur->_enabled_stock == 1) {
    $_SESSION['stock_err' . $idx] = 'Out of stock';
  }
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
* {
  font-family: Trebuchet MS;
  font-size: 12px;
}
table.list {
  border-left: 1px solid #aaa;
  border-top: 1px solid #aaa;
  font-size: 13px;
  width: 100%;
}
table.list th.sort {
  text-align: left;
  height: 28px;
  background-color: #ddd;
  padding: 0 5px; 
  border-right: 1px solid #aaa;
  border-bottom: 1px solid #aaa;
  font-weight: bold;
  vertical-align: middle;
  cursor: pointer;
  color: #333;
}
table.list tr.rowodd td {
  padding: 0 5px;
  height: 25px;
  background-color: #eee;
  border-right: 1px solid #aaa;
  border-bottom: 1px solid #aaa;
  word-wrap: break-word;
  vertical-align: middle;
  overflow: hidden;
}
table.list tr.roweven td {
  padding: 0 5px;
  height: 25px;
  background-color: #fff;
  border-right: 1px solid #aaa;
  border-bottom: 1px solid #aaa;
  word-wrap: break-word;
  vertical-align: middle;
}
table.list tr.rowodd:hover td {
  background-color: #f4f3b2;
}
table.list tr.roweven:hover td {
  background-color: #f4f3b2;
}
table.list tr.none td {
  padding: 0 5px;
  height: 25px;
  background-color: #fff;
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  word-wrap: break-word;
}
table.list input[type=text] {
  width: 99%;
  border: none;
}
div.wrap {
  padding: 5px 15px 25px 15px;
  background: #eee;
  border: 1px solid #ddd;
  width: 96%;
}
div.title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 5px;
  font-family: Lucida Sans Unicode;
}
.img {
  background:url(images/delete24.png) no-repeat;
  cursor:pointer;
  border: none;
  width: 100%;
  height: 24px;
}
.imgbtn {
  background-image: url(images/checkout.png);
  background-repeat: no-repeat;
  background-position: 5px 2px;
  padding: 5px 5px 5px 30px;
  border: 1px solid #666;
  background-color: #fff;
  cursor: pointer;
  border-radius: 3px;
  height: 45px;
  width: 155px;
  padding-left: 40px;
  font-family: Lucida Sans Unicode;
}
.imgbtn:hover {
  background-color: #eee;
}
.shop {
  background-image: url(images/shop.png);
  background-repeat: no-repeat;
}
.ccart {
  background-image: url(images/ccart.png);
  background-repeat: no-repeat;
}
.save {
  background-image: url(images/save.png);
  background-repeat: no-repeat;
}
form {
  padding: 0;
  margin: 0;
}
div.total {
  text-align: right;
}
div.total div {
  border: 1px solid #ddd;
  background: #fff;
  padding: 5px 10px;
  width: 350px;
  margin: 5px 0 0 auto;
  font-size: 14px;
  font-weight: bold;
}
div.total span.remind {
  display: block;
  color: #777;
  font-size: 12px;
  font-weight: normal;
}
div.total span.remind a {
  color: #777;
}
</style>
</head>
<body>
  <table cellpadding=0 cellspacing=0>
    <tr>
      <td style="width: 730px;vertical-align: top;">
        <div class="wrap">
          <div class="title">My Shopping Cart</div>
          <table id="cart" class="list" cellpadding=0 cellspacing=0>
            <tr>
              <th class="sort">ITEM</th>
              <th class="sort" style="width: 80px;">QTY</th>
              <th class="sort" style="width: 60px;">STOCK</th>
              <th class="sort" style="width: 60px;">EACH</th>
              <th class="sort" style="width: 90px;">TOTAL</th>
              <th class="sort" style="width: 40px;">&nbsp;</th>
            </tr>
            <?php foreach ($_SESSION['my_cart'] as $idx => $pur) { ?>
            <tr class="<?php echo (($idx % 2 == 0) ? 'roweven' : 'rowodd'); ?>">
              <td title="<?php echo $pur->name . (($pur->attr_opt_code != '') ? '(' . $pur->attr_opt_code . ')' : ''); ?>"><?php echo MiscUtils::getShortName($pur->name . (($pur->attr_opt_code != '') ? '(' . $pur->attr_opt_code . ')' : ''), 50); ?></td>
              <td>
                <input name="qty<?php echo $idx; ?>" id="qty<?php echo $idx; ?>" type="text" value="<?php echo $pur->quantity; ?>"></input>
                <?php if (isset($_SESSION['stock_err' . $idx])) { ?>
                <div style="color: red;"><?php echo $_SESSION['stock_err' . $idx]; ?></div>
                <?php } ?>
              </td>
              <td><?php echo (($pur->_enabled_stock == 1) ? $pur->_stock : 'Unlimited'); ?></td>
              <td>$<?php echo $pur->price; ?></td>
              <td id="total<?php echo $idx; ?>">$<?php echo sprintf("%01.2f", $pur->total); ?></td>
              <td>
                <form action="<?php echo basename(__FILE__, '.php'); ?>.server.php" method="post">
                  <input name="action" value="remove" style="display: none;"></input>
                  <input name="idx" value="<?php echo $idx; ?>" style="display: none;"></input>
                  <input name="to" value="<?php echo MiscUtils::curPageURL(); ?>" style="display: none;"></input>
                  <input type='submit' value="" class="img"></input>
                </form>
              </td>
            </tr>
            <?php } ?>
            <?php if (count($_SESSION['my_cart']) == 0) { ?>
            <tr class="none"><td colspan=6>None</td></tr>
            <?php } ?>
          </table>
          <div class="total">
            <div>
              Total: $<span id="cart_total"></span>
              <?php if (!isset($_SESSION['index' . USER])) { ?>
              <span class="remind">Not signed in? <a href="#" onclick="parent.location.href='http://<?php echo URL . '?i=' . LOGIN_ID . '&url='; ?>' + encodeURIComponent(parent.document.URL);">Sign in</a> or <a href="#" onclick="parent.location.href='http://<?php echo URL . '?i=' . LOGIN_ID . '&init=register&url='; ?>' + encodeURIComponent(parent.document.URL);">Register</a> for member discounts</span>
              <?php } ?>
            </div>
            
          </div>
        </div>
        <div>&nbsp;</div>
        <table style="width: 100%;" cellspacing=0 cellpadding=0>
          <tr>
            <td style="width: 155px;"><input type='submit' value="Continue Shopping" class="imgbtn shop" onclick="parent.location.href='http://<?php echo URL ?>'"></input></td>
            <td style="width: 155px; padding-left: 5px;">
              <form id="emptyform" action="<?php echo basename(__FILE__, '.php'); ?>.server.php" method="post">
                <input name="action" value="emptycart" style="display: none;"></input>
                <input name="to" value="<?php echo MiscUtils::curPageURL(); ?>" style="display: none;"></input>
                <input type='submit' value="Empty My Cart" class="imgbtn ccart">
              </form>
            </td>
            <td style="text-align: right;">
              <form action="<?php echo basename(__FILE__, '.php'); ?>.server.php" method="post">
                <input name="action" value="savenow" style="display: none;"></input>
                <input name="to" value="<?php echo MiscUtils::curPageURL(); ?>" style="display: none;"></input>
                <input id="last_cart2" name="last_cart" value="<?php echo htmlspecialchars(json_encode($_SESSION['my_cart'])); ?>" style="display: none;"></input>
                <input type='submit' value="Update My Cart" class="imgbtn save"></input>
              </form>
            </td>
            <td style="width: 155px; padding-left: 5px">
              <form action="<?php echo basename(__FILE__, '.php'); ?>.server.php" method="post">
                <input name="action" value="checkout" style="display: none;"></input>
                <input name="to" value="http://<?php echo URL . '?i=' . $page_id . '&script=index_login' ?>" style="display: none;"></input>
                <input name="from" value="<?php echo MiscUtils::curPageURL(); ?>" style="display: none;"></input>
                <input id="last_cart" name="last_cart" value="<?php echo htmlspecialchars(json_encode($_SESSION['my_cart'])); ?>" style="display: none;"></input>
                <input type='submit' value="Checkout" class="imgbtn"></input>
              </form>
            </td>
          </tr>
        </table>
      </td>
      <td style="width: 230px;vertical-align: top;"><?php include dirname(__FILE__) . '/inc.right.php'?></td>
    </tr>
  </table>
<script src="../../../libs/jquery/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="../../../incls/js/myutils.js"></script>
<script type="text/javascript" src="../../../libs/json/json2.js"></script>
<link href="jquery_ui/css/smoothness/jquery-ui-1.10.2.custom.css" rel="stylesheet">
<script src="../../../libs/jquery_ui/js/jquery-ui-1.10.2.custom.js"></script>
<script type="text/javascript">
  var _cart = JSON.parse('<?php echo addslashes(json_encode($_SESSION['my_cart'])); ?>');
  var _objects = JSON.parse('<?php echo isset($objects) ? addslashes(json_encode($objects)) : '[]'; ?>');
  
  $(function(){
    parent.document.title = parent.document.title.replace('Product', 'My Shopping Cart')

    $('#emptyform').submit(function(e) {
      if (!window.confirm('Are You Sure?')) {
        e.preventDefault();
        return false;
      }
    });
    
    for (var idx in _cart) {
      var MIN = 1;
      $('#qty' + idx).spinner({ min: MIN });
      $('#qty' + idx).on('keyup', function(e) {
        var v = parseInt($(this).val());
        if (isNaN(v)) {
           return $(this).val(MIN);
        }
        if ($(this).val() < MIN) {
           $(this).val(MIN);
        } else {
           $(this).val(v);
        }
        update_purchase(this, this.value);
      });
      $( "#qty" + idx ).spinner({
        spin: function( event, ui ) { 
        update_purchase(this, ui.value);
        }
      });
    }
    update_total();
  });
  
  function update_purchase(qtyElm, value) {
    var num = qtyElm.id.replace('qty', '');
    MyUtils.removeChildElements($('#total' + num)[0]);

    _cart[num].quantity = value;
    _cart[num].total = _cart[num].quantity * _cart[num].price;

    $('#last_cart')[0].value = JSON.stringify(_cart);
    $('#last_cart2')[0].value = JSON.stringify(_cart);
    $('#total' + num)[0].appendChild(document.createTextNode('$' + (_cart[num].total).toFixed(2))); 
    update_total();
  }

  function update_total() {
    var total = 0;
    for (var idx in _cart) {
      var obj = _cart[idx];
      total += parseFloat(obj.total, 2);
    }
    MyUtils.removeChildElements($('#cart_total')[0]);
    $('#cart_total')[0].appendChild(document.createTextNode(total.toFixed(2)));
  }
</script>
</body>
</html>